//
//  TYHttpError.m
//  YDGJ
//
//  Created by 黄卫 on 17/2/24.
//  Copyright © 2017年 huangwei. All rights reserved.
//

#import "TYHttpError.h"

/** 跳转重新登录*/
#import "TYCustomNavgationCotr.h"
//#import "GJLoginVC.h"

@implementation TYHttpError

/**
 *  封装服务器数据错误信息
 */
+(TYHttpError *)getTYHttpErrorByServerError:(NSError *)error serverCode:(NSInteger)serverCode serverTip:(NSString *)serverTip
{
    NSString *errorMsg = @"";
    NSInteger errorCode = -2015000;
    NSDictionary *userInfo = nil;
    
    if (error) { //网络底层请求出错 -> (网络请求,错误回调返回的错)
        errorMsg = [error.domain isEqualToString:@"NSURLErrorDomain"] ? @"服务器内部繁忙,请稍后重试" : error.domain;
        errorCode = error.code;
        userInfo = error.userInfo;
        
    } else { // 服务器请求失败 -> (网络请求,非0,200的返回码)
        errorCode = serverCode;
        errorMsg = serverTip;
    }
    
    //规避两个错误码一样而不能退出登录的问题
    if (errorCode == Code_ShopUExist) {
        if ([errorMsg rangeOfString:HasSameShopNameError].location != NSNotFound ||
            [errorMsg rangeOfString:@"登录账户已经存在"].location != NSNotFound)
        {
            errorCode = -errorCode;
        }
    }
    
    //在这里自定义错误码的提示信息
    switch (errorCode) {
        case -1011:
        {
            errorMsg = ServerConnectFail;
        }
            break;
            
        case -1001:
        case -1004:
        {
            errorMsg = RequestTimeOut;
        }
            break;
            
        case Code_AgainLoginThree:      //请求错误需要重新登录
        case Code_AgainLoginFour:       //请求错误需要重新登录
        case Code_AgainLoginsFifth:     //请求错误需要重新登录
//        case Code_ShopUExist:           //请求错误需要重新登录 <警告:正式打包要干掉50001错误码的判断>
        {
            NSLog(@"处理服务端特殊Code");
            [self needALogOutByError:errorMsg];
        }
            break;
            
        case GJNoInterneErrorCode: //网络连接失败
        {
            errorMsg = NetworkConnectFail;
        }
            break;
            
        default:
            break;
    }
    
    if (errorMsg == nil) {
        errorMsg = @"";//Domain不能为空
    }
    
    TYHttpError *httpError = [[TYHttpError alloc] initWithDomain:errorMsg code:errorCode userInfo:userInfo];
    httpError.errorMsg = errorMsg;
    httpError.errorCode = errorCode;
    
    return httpError;
}

#pragma mark - http 服务端特殊Code 需要重新登录操作处理

+(void)needALogOutByError:(NSString *)errorTip
{
    //根据iOS系统版本弹框
    [GJAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
        
        //注销登录处理
        [TYGlobalManager logoutDealWithFMDB];
        
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
//        [window setRootViewController:[[GJCustomNavgationCotr alloc]initWithRootViewController:[GJLoginVC new]]];
        
    } title:errorTip message:nil cancelButtonName:nil otherButtonTitles:@"确定", nil];
}

@end
